package com.Final.hj;


import android.app.ListActivity;
import android.content.Context;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.AbsListView;
import android.widget.AdapterView;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.SeekBar;
import android.widget.TextView;
import android.widget.Toast;

import com.bumptech.glide.Glide;
import com.bumptech.glide.load.engine.DiskCacheStrategy;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;

import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.FormBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;


/**
 * A simple {@link Fragment} subclass.
 */
public class MusicApp extends ListActivity implements AbsListView.OnScrollListener {

    private static final int SEACH_MUSIC = 1;
    private static final int SEACH_ERR = 0;


    private EditText music_seach_et;
    private TextView music_seach_btn;
    private static final String TAG = "OkHttp3";
    //歌曲每页限制条数 和 第几页
    private int pageSize = 10;
    private int page = 0;//默认0页
    //当前的content
    private Context musicContent;

    //音频MediaPlayer
    private MediaPlayer mediaPlayer;
    //暂停|播放、下一首、上一首按钮
    private ImageView music_play_pasu, music_prev, music_next, music_b_img;
    private TextView music_b_name, music_b_s_name, music_time, music_total_time;
    private SeekBar music_seekBar;

    private int musicId = 0;
    private String myId;


    //创建一个适配器
    private MusicAdapter adapter;
    //列表显示的歌曲。因为当
    private List<MusicList.Data> musicListData = new ArrayList<>();
    //这个是播放列表的所拿的数据 只有点击了item才会重新赋值
    private List<MusicList.Data> musicListPlayData = new ArrayList<>();
    private MusicList.Data musicItem;//当前点击项


    //加载更多的变量
    private int visibleLastIndex = 0;   //最后的可视项索引
    private int visibleItemCount;       // 当前窗口可见项总数
    private View loadMoreView;//加载更多的适配器
    private Timer timer;//定时器
    private TimerTask task;

    //listView
    private ListView music_list;
    private String keyWord = "不在犹豫";
    private boolean seachFlag = true;
    private int musicLength;//歌曲长度
    private String musicTextTime;//歌曲长度 00：00格式
    private boolean isSetSeekBar = false;//是否在拖动进度条  默认不拖动

    private InitMusic initMusicData;//进入歌曲的初始化内容


    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState)  {
        super.onCreate(savedInstanceState);

        setContentView(R.layout.music_app);
        musicContent = this;
        initView();
//        getInitMusic();


        music_list.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
               System.out.print(position);

               //当当前点击是播放歌曲，不应该再次设置，应该暂停歌曲
               if(musicId == position){
                   return;
               }

                //保存当前歌曲id
                musicId = position;
                handler.sendEmptyMessage(1);
            }
        });
    }

    //音乐播放函数
    public void musicPlay(){
        //获取当前点击的Data对象
        musicItem = musicListData.get(musicId);

        //歌曲长度
        musicLength = Integer.parseInt(musicItem.getTime()) * 1000;//这里获取的是秒数
        musicTextTime = getFormatime(musicLength);//获取歌曲长度 00：00
        toastMsg(musicTextTime);
        //音乐的播放
        try {
            mediaPlayer.reset();
            mediaPlayer.setDataSource(musicItem.getUrl());
            mediaPlayer.prepare();
            mediaPlayer.start();

        } catch (IOException e) {
            e.printStackTrace();
        }

        //设置图片
        Glide.with(musicContent)
                .load(musicItem.getPic())
                .skipMemoryCache(true)
                .diskCacheStrategy(DiskCacheStrategy.NONE)
                .into(music_b_img);


        music_b_name.setText(musicItem.getName());
        music_b_s_name.setText(musicItem.getSinger());

        music_total_time.setText(musicTextTime);
        //设置进度条的最大值
        music_seekBar.setMax(musicLength);
        //图标打开
        music_play_pasu.setImageResource(R.drawable.play);
        setSeekBar();
    }

    /*
        上一首 下一首 暂停播放
     */

    //上一首
    public void musicPrev(View v){
        if(mediaPlayer != null && musicId <= 0){
            toastMsg("当前歌曲已经是第一首了，不能往前啦");
            return;
        }

        musicId = musicId - 1;
        handler.sendEmptyMessage(1);
    }

    //暂停 播放
    public void musicPlayPasu(View v){

        if(mediaPlayer != null && musicItem != null){
            handler.sendEmptyMessage(2);
            return;
        }

        toastMsg("暂无歌曲可以播放");
    }

    //下一首
    public void musicNext(View v){
        if(mediaPlayer != null && musicId >= musicListData.size() - 1){
            toastMsg("当前歌曲已经是最后了，要回头啦");
            return;
        }
        musicId = musicId + 1;
       handler.sendEmptyMessage(1);
    }


    //初始化 歌曲  进入应用的时候初始化歌曲
    public void initmusic(String data){

        if(data.equals("0")){
            musicItem = null;
            return;
        }


        //显示相应的数据
        //并且发送请求 拿取当前歌曲的所有信息
        String[] musicData = data.split(",_");

        musicListData.add(new MusicList.Data(musicData[0], musicData[1], musicData[2], musicData[3], musicData[4], musicData[5], musicData[6]));
        handler.sendEmptyMessage(4);
    }

    //子线程更新ui
    private Handler handler=new Handler(){
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what){
                case 0:
                    //默认第一次是搜索的
                    if(seachFlag) {
                        adapter = new MusicAdapter(musicContent, R.layout.music_list_adapter, musicListData);
                        music_list.setAdapter(adapter);
                    }else{
                        //这里是加载更多  更新数据
                        adapter.notifyDataSetChanged();
                    }
                    break;
                case 1:
                    //每次点击更新界面
                    //这里是点击每一项播放的 因此需要显示播放按钮
                    music_play_pasu.setImageResource(R.drawable.play);
                    musicPlay();
                    break;
                case 2:
                    //暂停歌曲 或者播放歌曲
                    //需要判断一下 歌曲是否在播放
                    if(!mediaPlayer.isPlaying()){
                        //此时是暂停 开始播放
                        mediaPlayer.start();
                        //显示播放图标
                        music_play_pasu.setImageResource(R.drawable.play);
                        //并且调用
                        setSeekBar();
                    }else{
                        //否则暂停
                        mediaPlayer.pause();
                        if (timer != null){
                            timer.cancel();
                            timer = null;
                            task.cancel();
                            task = null;
                        }
                        //显示暂停图标
                        music_play_pasu.setImageResource(R.drawable.pasu);
                    }
                    break;
                case 3:
                    //更新播放进度条
                    music_seekBar.setProgress(mediaPlayer.getCurrentPosition());
                    music_time.setText(getFormatime(mediaPlayer.getCurrentPosition()));
                    break;
                case 4:
                    musicPlay();
                    break;
            }
        }
    };



//    下面是刷新数据功能
    /**
     * 滑动时被调用
     */
    @Override
    public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) {
        this.visibleItemCount = visibleItemCount;
        visibleLastIndex = firstVisibleItem + visibleItemCount - 1;
    }

    /**
     * 滑动状态改变时被调用
     */
    @Override
    public void onScrollStateChanged(AbsListView view, int scrollState) {

        int itemsLastIndex = adapter.getCount() - 1;    //数据集最后一项的索引
        int lastIndex = itemsLastIndex + 1;             //加上底部的loadMoreView项
        if (scrollState == AbsListView.OnScrollListener.SCROLL_STATE_IDLE && visibleLastIndex == lastIndex) {
            //此时一到达底部就会调用  这里是加载更多
            seachFlag = false;
            //发送请求获取更多数据
            page = page + 1;
            sendHttp();
            Toast.makeText(MusicApp.this, "加载中", Toast.LENGTH_SHORT).show();
        }
    }

    //搜索歌曲
    public void seachMusic(){
        //这里发送酷狗请求
        keyWord = music_seach_et.getText().toString().trim();
        //搜索歌曲把之前的清空掉
        musicListData.clear();
        page = 0;//初始化获取第一页数据

        if(TextUtils.isEmpty(keyWord)){
            Toast.makeText(musicContent, "请输入歌曲名字", Toast.LENGTH_LONG).show();
            return;
        }
        seachFlag = true;
        sendHttp();
    }

    public void sendHttp(){

        new Thread(new Runnable() {
            @Override
            public void run() {
                try{
                    //https://v1.itooi.cn/kugou/search?keyword=%E5%85%89%E8%BE%89%E5%B2%81%E6%9C%88&type=song&pageSize=1&page=0&format=1
                    OkHttpClient client = new OkHttpClient();
                    String url = "https://v1.itooi.cn/kugou/search?keyword="+
                            keyWord+"&pageSize="+pageSize+"&page="+page+"&type=song&format=1";
                    Request request = new Request.Builder()
                            .url(url)
                            .build();

                    Call call = client.newCall(request);
                    call.enqueue(new Callback(){
                        @Override
                        public void onFailure(Call call, IOException e) {
                            Log.i("TAG", e.toString());
                        }
                        @Override
                        public void onResponse(Call call, Response response) throws IOException {
                            String string = response.body().string();
                            //调用函数解析json
                            parseMusic(string);
                        }
                    });
                }catch (Exception e){
                    e.printStackTrace();
                    System.out.println("获取歌曲失败");
                }
            }
        }).start();
    }

    //获取上一次数据歌曲信息
    public void getInitMusic(){
        new Thread(new Runnable() {
            @Override
            public void run() {
                try{
                    //https://v1.itooi.cn/kugou/search?keyword=%E5%85%89%E8%BE%89%E5%B2%81%E6%9C%88&type=song&pageSize=1&page=0&format=1
                    OkHttpClient client = new OkHttpClient();
                    String url = "http://192.168.43.124:8080/gmusic";
                    Request request = new Request.Builder()
                            .url(url)
                            .build();
                    Call call = client.newCall(request);
                    call.enqueue(new Callback(){
                        @Override
                        public void onFailure(Call call, IOException e) {
                            Log.i("TAG", e.toString());
                        }
                        @Override
                        public void onResponse(Call call, Response response) throws IOException {
                            String string = response.body().string();
                            //调用函数解析json
                            initmusic(string);
                        }
                    });
                }catch (Exception e){
                    e.printStackTrace();
                    System.out.println("获取歌曲失败");
                }
            }
        }).start();
    }

    public void parseMusic(String strJson){
        Gson gson = new Gson();
        java.lang.reflect.Type type = new TypeToken<MusicList>(){}.getType();
        MusicList musicList = gson.fromJson(strJson, type);

        System.out.println("解析完成");

        List<MusicList.Data> musicData = musicList.getData();
        musicListData.addAll(musicData);


        handler.sendEmptyMessage(0);
    }

    @Override
    protected void onStop() {
        super.onStop();

    }

    @Override
    protected void onDestroy() {
        super.onDestroy();

        //释放资源
        if (mediaPlayer != null) {
            mediaPlayer.stop();
            mediaPlayer.release();
            mediaPlayer = null;
        }

        if (timer != null){
            timer.cancel();
            timer = null;
            task.cancel();
            task = null;
        }
    }

    //初始化变量
    public void initView(){
        music_seach_et = (EditText) findViewById(R.id.seachEdit);
        music_seach_btn = (TextView) findViewById(R.id.seachBtn);
//        music_list = (ListView) findViewById(R.id.music_List);

        //播放控件
        music_play_pasu = (ImageView) findViewById(R.id.music_play_pasu);
        music_next= (ImageView) findViewById(R.id.music_next);
        music_prev = (ImageView) findViewById(R.id.music_prev);
        music_b_img = (ImageView) findViewById(R.id.music_b_img);

        music_b_name = (TextView) findViewById(R.id.music_bottom_name);
        music_b_s_name = (TextView) findViewById(R.id.music_bottom_singer_name);

//        进度条
        music_time = (TextView) findViewById(R.id.music_time);
        music_total_time = (TextView) findViewById(R.id.music_total_time);
        music_seekBar = (SeekBar) findViewById(R.id.music_seekBar);


        mediaPlayer = new MediaPlayer();

        myId = LoginSQLManger.getInstance(MusicApp.this).queryAll().getMyId();

        music_seach_btn.setOnClickListener(new View.OnClickListener(){
            @Override
            public void onClick(View view){
                Toast.makeText(musicContent, "点击了", Toast.LENGTH_LONG).show();
                seachMusic();
            }
        });

        music_list = getListView();
        //底部加载
        loadMoreView = getLayoutInflater().inflate(R.layout.load_more, null);
//        loadMoreButton = (Button) loadMoreView.findViewById(R.id.loadMoreButton);
        music_list.addFooterView(loadMoreView);
        //监听滑动
        music_list.setOnScrollListener(this);     //添加滑动监听
        music_seekBar.setOnSeekBarChangeListener(new MySeekBar());
    }
    //把时间转为00:00的格式显示出来
    private String getFormatime(int lengrh) {
        Date date = new Date(lengrh);
        SimpleDateFormat sdf = new SimpleDateFormat("mm:ss");
        String totalTime = sdf.format(date);
        //并返回该时间
        return totalTime;
    }
    //Tosat提示
    public void toastMsg(String msg){
        Toast.makeText(MusicApp.this, msg, Toast.LENGTH_SHORT).show();
    }

    //监听音乐播放设置进度条 以及 播放时间设置
    public void setSeekBar(){
        if(timer != null && task != null){
            return;
        }
        timer = new Timer();
        //50s执行一次
        task = new TimerTask() {
            @Override
            public void run() {
                //此时要跟新ui界面
                if(!isSetSeekBar){//不在设置
                    handler.sendEmptyMessage(3);
                }
            }
        };
        timer.schedule(task, 0, 1000);
    }

    /*进度条处理 music_seekBar 创建该实例即可*/
    public class MySeekBar implements SeekBar.OnSeekBarChangeListener {

        public void onProgressChanged(SeekBar seekBar, int progress,
                                      boolean fromUser) {
            //seekBar即为当前seekBar  ， progress 即为 拖动的数值   fromUser标志用户是否拖动
//            if(fromUser) {//最好不要在这里设置它 因为 这样会一直触发 卡顿
//                mediaPlayer.seekTo(progress);
//            }
        }

        /*滚动时,应当暂停后台定时器*/
        public void onStartTrackingTouch(SeekBar seekBar) {
            //这里关闭定时器即可
            isSetSeekBar = true;
        }
        /*滑动结束后，重新设置值*/
        public void onStopTrackingTouch(SeekBar seekBar) {
            //设置为false
            isSetSeekBar = false;
            //设置播放时间
            mediaPlayer.seekTo(seekBar.getProgress());
            toastMsg("获得了");
        }
    }

    //返回首页
    public void backHome(View v){
        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    OkHttpClient client = new OkHttpClient();

                    RequestBody requestBody = new FormBody.Builder()
                            .add("id", myId)
                            .add("name", musicItem.getName())
                            .add("singer", musicItem.getSinger())
                            .add("url", musicItem.getUrl())
                            .add("pic", musicItem.getPic())
                            .add("maxTime", musicItem.getTime())//歌曲的时间长度
                            .add("playTime", String.valueOf(mediaPlayer.getCurrentPosition()))//播放时间 毫秒 此时就是歌词
                            .build();
                    Request request = new Request.Builder()
                            .url("http://192.168.43.124:8080/gmusic")
                            .post(requestBody)
                            .build();

                    Response response = client.newCall(request).execute();
                    String string = response.body().string();
                    System.out.print(string);
                }catch (Exception e){
                    e.printStackTrace();
                }

            }
        });
//        Intent intent = new Intent(MusicApp.this, HomeActivity.class);
           MusicApp.this.finish();
//        startActivity(intent);
    }
}
